<script setup name="AsInput">
  // 该组件用于搭配vxe-table使用
  // 以对el-input变量与事件插槽ref进行透传(多数情况下组件可复用, 直接在组件上使用el-input的属性/事件/插槽即可,ref临时解决方案: 嵌套inputRef)
  // 若业务复杂, 使用el-input自行处理
  import { ref, computed, watch } from 'vue'
  const props = defineProps({
    column: {
      type: Object,
      default: () => [],
    },
    iconWidth: {
      type: Number,
      default: 0,
    },
    // 输入完后是否立即触发事件(无需回车)
    immediate: {
      type: Boolean,
      default: false,
    },
  })

  const asValue = ref(props.column)
  watch(
    () => props.column,
    (newValue, oldValue) => {
      asValue.value = newValue
    },
    {
      immediate: true,
      deep: true,
    }
  )

  const emit = defineEmits(['change'])

  function debounce(func, delay) {
    let timer = null
    return function (...args) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        func.apply(this, args)
      }, delay)
    }
  }

  const inputRef = ref(null)
  // 修复enter与input触发两次
  const handleFilterChangeEvent = debounce((params, status) => emit('change', params, status), 500)

  setTimeout(() => {
    console.log(inputRef.value)
  }, 1000)

  const styleEl = computed(() => ({ display: 'inline-block', width: `calc(100% - ${props.iconWidth}px)` }))
  defineExpose({ inputRef })
</script>

<template>
  <el-input
    ref="inputRef"
    v-bind="$attrs"
    :style="styleEl"
    v-model="column.filters[0].data"
    @input="handleFilterChangeEvent(column.filters[0], immediate)"
    @keyup.enter="handleFilterChangeEvent(column.filters[0], true)"
  >
    <template v-for="(_, slot) in $slots" #[slot]="slotProps" :key="slot">
      <slot :name="slot" v-bind="slotProps ?? {}"></slot>
    </template>
  </el-input>
</template>
